import os
import uuid
import re
import IPy
from mac.models import Macs
# board = "B42"
# country = "CN"


def randomMAC(*args):
    '''
    生成数据
    :param mac:
    :param mac_nums:
    :param ip:
    :param uuid:
    :return:
    '''
    random_mac_list = []
    model = args[4].model
    board = args[4].board
    country = args[4].country
    deviceid = args[4].device_id
    secret = args[4].device_id_pwd
    mqtt = args[4].mqtt
    mark = args[4].mark
    public_key = args[4].pubkey
    endpoint_host = args[4].endpoint_host
    endpoint_port = args[4].endpoint_port
    future = args[4].future
    i = 0
    while i < int(args[2]):
        ii = i * args[4].mac_inc
        random_mac_dict = {}
        new_mac = handle_mac(args[1], ii)
        str_uuid = str(uuid.uuid4())
        uuid_mac = str_uuid.replace(str_uuid[-12:], new_mac)
        random_mac_dict["mac"] = new_mac.upper()
        random_mac_dict["uuid"] = uuid_mac
        random_mac_dict["model"] = model
        random_mac_dict["board"] = board
        random_mac_dict["country"] = country
        random_mac_dict["deviceid"] = deviceid
        random_mac_dict["secret"] = secret
        random_mac_dict["mqtt"] = mqtt
        random_mac_dict['mark'] = mark
        random_mac_dict["public_key"] = public_key
        if args[3]:
            ip_str = handle_ip(args[3], i)
            ip_str1 = ip_str + "/32"
            random_mac_dict["address"] = ip_str1
        else:
            random_mac_dict['address'] = None
        random_mac_dict["endpoint_host"] = endpoint_host
        random_mac_dict["endpoint_port"] = endpoint_port
        random_mac_dict["future"] = future
        if args[4].mark1 in (1, 2):
            private_key = None
            dutpublic_key = None
        else:
            # create prikey dir
            dirs = 'key'
            if not os.path.exists(dirs):
                os.mkdir(dirs)
            priv = "./key/%s.prib" % new_mac
            pubk = "./key/%s.pubk" % new_mac
            pri = os.system("wg genkey > %s" % priv)
            pubki = os.system("wg pubkey < %s > %s" % (priv, pubk))
            # get privkey
            with open(priv, "r") as f:
                private_key = f.read().strip()
            # get pubkey
            with open(pubk, "r") as f:
                dutpublic_key = f.read().strip()
        random_mac_dict["private_key"] = private_key
        random_mac_dict["dutpublic_key"] = dutpublic_key
        random_mac_list.append(random_mac_dict)
        i += 1
    if args[3]:
        ip_str = handle_ip(ip_str, 1)
    else:
        ip_str = None
    return random_mac_list, ip_str


def handle_mac(mac, ii):
    '''
    处理MAC
    :param mac:
    :param ii:
    :return:
    '''
    mac_int = int(mac, 16)
    new_mac_int = mac_int + ii
    if not mac.startswith('0'):
        mac = hex(new_mac_int).replace('0x', '')
    else:
        m = re.match(r'^[0]+', mac)
        if m:
            mac = hex(new_mac_int).replace('0x', m.group(0))
    return mac


def handle_ip(ip, i):
    '''
    处理IP
    :param ip:
    :param i:
    :return:
    '''
    # ip_lst = ip.split('.')
    # ip_end = int(ip_lst[3]) + i
    # if ip_end > 255 and ip_end % 255 != 0:
    #     ip_end_remainder = (ip_end % 255) - 1
    #     # print(ip_end_remainder)
    #     ip_lst[3] = str(ip_end_remainder)
    #     ip_lst_2 = str(int(ip_lst[2]) + ip_end // 255)
    #     ip_lst[2] = ip_lst_2
    # elif ip_end > 255 and ip_end % 255 == 0:
    #     ip_end_remainder = 255
    #     ip_lst[3] = str(ip_end_remainder)
    #     ip_lst_2 = str(int(ip_lst[2]) - 1 + ip_end // 255)
    #     ip_lst[2] = ip_lst_2
    # else:
    #     ip_lst[3] = str(ip_end)
    # ip_str = '.'.join(ip_lst)
    # return ip_str
    ip_int = IPy.IP(ip).int()
    ip_int += i
    ip_str = IPy.IP(ip_int)
    return str(ip_str)


def writeDict(*args):
    '''
    把数据写入数据库Macs表中
    :param mac:
    :param mac_nums:
    :param ip:
    :return:
    '''
    random_mac_list, ip_str = randomMAC(*args)
    mac_obj_list = [Macs(**item) for item in random_mac_list]
    Macs.objects.bulk_create(mac_obj_list, batch_size=500)
    return ip_str


def main(*args):
    '''
    脚本主入口
    :param mac:
    :param mac_nums:
    :param ip:
    :return:
    '''
    return writeDict(*args)




